using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Coderoom.ScrumPlanner.Data.Contracts;
using Coderoom.ScrumPlanner.Domain;
using Coderoom.ScrumPlanner.Domain.Validation;
using Coderoom.ScrumPlanner.Resources;

namespace Coderoom.ScrumPlanner.Data
{
	public sealed class ProjectService : Service<IProjectRepository>
	{
		public ProjectService(IProjectRepository repository) : base(repository) {}

		[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
		public ProjectCollection GetProjects()
		{
			return Repository.GetProjects();
		}

		public Project GetProject(Guid projectId)
		{
			return Repository.GetProject(projectId);
		}

		public Project GetProject(string slug)
		{
			if (slug == null)
				throw new ArgumentNullException("slug");

			return Repository.GetProject(slug);
		}

		public OperationResult CreateProject(Project project)
		{
			if (project == null)
				throw new ArgumentNullException("project");

			var validationResult = EntityValidator.Validate(project);

			if (!SlugIsUnique(project.Slug))
			{
				validationResult.IsValid = false;
				validationResult.Errors.Add(new ValidationError{ Message = ValidationMessages.Entity_SlugInUse, PropertyName = "Slug", ValidationTarget = project});
			}

			if (validationResult.IsValid)
			{
				Repository.CreateProject(project);
				return new OperationResult(true);
			}
			
			return new OperationResult(false, validationResult.Errors);
		}

		public bool DeleteProject(Guid projectId)
		{
			return Repository.DeleteProject(projectId);
		}

		public bool DeleteProject(string slug)
		{
			if (slug == null)
				throw new ArgumentNullException("slug");

			return Repository.DeleteProject(slug);
		}

		private bool SlugIsUnique(string slug)
		{
			return GetProjects().Where(project => project.Slug == slug).Count() == 0;
		}
	}
}